
//  Created by 邓盛明 on 2022/1/11.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

public class TF_AnswerCardView: UIView {
    @objc public var submitBtn:UIButton!//提交
    @objc public var answerSuccessView:UIView! //答题成功
    @objc public var answerView:UIView! //答题view
    @objc public var optional:TalkfunTopicType = TalkfunTopicTypeIndividualEvent //单选还是多选
    var selectArr:NSMutableArray = NSMutableArray.init()
    var titleLab:UILabel!
    var timeLab:UILabel!
    var closeBtn:UIButton!
    var lineView:UIView!
    var answerCardView:UIView!  //答题框
    var successImg:UIImageView!  //答题成功
    var successLab:UILabel!
    var answerTimer:Timer! //提交成功的
    var Detailmodel:TFExaminationDetail!
    var completion_url:String!
    var buttonArr:[UIButton] = [];
    @objc public var answerCardId:NSInteger = 0;
    var timer:Timer!
    var endTime:NSInteger = 0
    
    @objc public var fastPaperDetailsSelectBlock:TestPaperDetailsSelectBlock?
    @objc public var closeBlock: ZSTapGestureBlock?
    @objc public var endBlock: ZSTapGestureBlock?
    @objc public var countdownEndView:UIView! //答题已结束
    var endLab:UILabel!
 
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.layer.cornerRadius = 8;
        self.layer.masksToBounds = true
        self.answerView = UIView.init()
        self.addSubview(self.answerView)
      
        self.answerSuccessView = UIView.init()
        self.answerSuccessView.layer.borderColor = UIColor(red: 224/255.0, green: 233/255.0, blue: 239/255.0, alpha: 1.0).cgColor
        self.answerSuccessView.layer.cornerRadius = 10;
        self.answerSuccessView.layer.borderWidth = 0.5;
        self.answerSuccessView.layer.shadowRadius = 15;
        self.answerSuccessView.layer.shadowOpacity = 1;
        self.answerSuccessView.layer.shadowColor = UIColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 0.2).cgColor
        self.answerSuccessView.layer.shadowOffset = CGSize(width: 0, height: 0)
        self.answerSuccessView.isHidden = true
        self.addSubview(self.answerSuccessView)
        
        self.countdownEndView = UIView.init();
        addSubview(self.countdownEndView)
        self.countdownEndView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.7);
        self.countdownEndView.layer.masksToBounds = true
        self.countdownEndView.layer.cornerRadius = 4
        self.countdownEndView.isHidden = true
        self.endLab = UILabel.init()
        self.endLab.text = "答题已结束"
        self.endLab.textAlignment = .center;
        self.endLab.textColor = UIColor.white
        self.endLab.font = UIFont.PingFang(size: 16)
        self.countdownEndView.addSubview(self.endLab);
        
        
        self.successImg = UIImageView.init()
        self.successImg.image = UIImage.init(named: "HTLive.bundle/responderSuccess")
        self.answerSuccessView.addSubview(self.successImg)
         
        self.successLab = UILabel.init()
        self.successLab.text = "答题成功";
        self.successLab.textAlignment = .center
        self.successLab.textColor = UIColor(red: 78/255.0, green: 92/255.0, blue: 103/255.0, alpha: 1.0)
        self.successLab.font = UIFont.PingFang(size: 16)
        self.answerSuccessView.addSubview(self.successLab)

        self.titleLab = UILabel.init()
        self.titleLab.text = "多选题";
        self.titleLab.textColor = UIColor(red: 78/255.0, green: 92/255.0, blue: 103/255.0, alpha: 1.0)
        self.titleLab.font = UIFont.PingFang(size: 16)
        self.answerView.addSubview(self.titleLab)
      
        self.timeLab = UILabel.init()
        self.timeLab.text = "倒计时:"
        self.timeLab.textColor = UIColor(red: 108/255.0, green: 127/255.0, blue: 141/255.0, alpha: 1.0)
        self.timeLab.font = UIFont.PingFang(size: 14)
        self.answerView.addSubview(self.timeLab)
        self.closeBtn = UIButton.init()
        self.closeBtn.setImage(UIImage.init(named: "HTLive.bundle/close_gray"), for: .normal)
        self.closeBtn.addTarget(self, action: #selector(clostBtnClick), for: .touchUpInside)
        self.answerView.addSubview(self.closeBtn)

        self.answerCardView = UIView.init()
        self.answerView.addSubview(self.answerCardView)
      
        self.lineView = UIView.init()
        self.lineView.alpha = 1.0;
        self.lineView.backgroundColor = UIColor(red: 237/255.0, green: 240/255.0, blue: 243/255.0, alpha: 1.0)
        self.lineView.layer.cornerRadius = 4;
        self.answerView.addSubview(self.lineView)
      
        self.submitBtn = UIButton.init()
        self.submitBtn.setTitle("提交", for: .normal)
        self.submitBtn.setTitleColor(UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1.0), for: .normal)
        self.submitBtn.titleLabel?.font = UIFont.PingFang(size: 18)
        self.submitBtn.addTarget(self, action: #selector(subminClick), for: .touchUpInside)
        self.answerView.addSubview(self.submitBtn)
        
    }
    
   @objc func subminClick()  {
     
       let answerModel = self.Detailmodel.subjectDetailList[0]
//       let completion_url = self.Detailmodel.access.completion_url
       let arr = NSMutableArray.init()
     
       for i in 0..<self.buttonArr.count {
           let btn1 = self.buttonArr[i]
           let m2 = answerModel.subjectAnswerList[i] as? TalkfunSubjectAnswer
           if btn1.isSelected == true {
               arr.add(NSString.init(format: "%i", m2!.id))
           }
       }
      
       if self.fastPaperDetailsSelectBlock != nil {
         
           let str:NSInteger = (answerModel.subjectInfo.id)
           self.fastPaperDetailsSelectBlock!(str,arr,self.Detailmodel.access.access_key as NSString,"")
           
       }
       
    }
    
    public override func layoutSubviews() {
        super.layoutSubviews()
        self.answerView.frame = self.bounds;
        self.answerSuccessView.frame = self.bounds;
        self.countdownEndView.frame = self.bounds;
        self.endLab.frame = CGRect(x: 20, y: 10, width: self.frame.size.width-40, height: self.frame.size.height-20)
        
        self.titleLab.frame = CGRect(x: 15, y: 12, width: 50, height: 22)
        self.timeLab.frame = CGRect(x: self.titleLab.frame.maxX+10, y: 12, width: 150, height: 22)
        self.closeBtn.frame = CGRect(x: self.frame.size.width-22-10, y: 12, width: 22, height: 22)
        self.answerCardView.frame = CGRect(x: 0, y: self.titleLab.frame.maxY, width: self.frame.size.width, height: self.frame.size.height-50-0.5-self.titleLab.frame.maxY)
        self.lineView.frame = CGRect(x: 0, y: self.answerCardView.frame.maxY, width: self.frame.size.width, height: 0.5)
        self.submitBtn.frame = CGRect(x: 0, y: self.frame.size.height-50, width: self.frame.size.width, height: 50)
        
        self.successImg.frame = CGRect(x: (self.frame.size.width-66)/2.0, y: 20, width: 66, height: 66)
        self.successLab.frame = CGRect(x: 0, y: self.successImg.frame.maxY+15, width: self.frame.size.width, height: 22)
    }
    
    @objc func clostBtnClick()  {
        if self.closeBlock != nil {
            self.closeBlock!()
        }
      
        if self.answerTimer != nil {
            self.answerTimer.invalidate()
            self.answerTimer = nil
        }
        if self.timer != nil {
            self.timer.invalidate()
            self.timer = nil;
        }
    }
    
    //数据来源
    @objc public func setAnswerCard(_ model:TFExaminationDetail) {
        self.Detailmodel = model
 
        self.buttonArr.removeAll()
        self.layoutSubviews()
        self.answerCardView.subviews.forEach { subview in
            subview.removeFromSuperview()
        }
       
        let answerModel = self.Detailmodel.subjectDetailList[0]
        self.optional = (answerModel.subjectInfo.type)
        
        self.createButton(answerModel)
    
    }
    
    func createButton(_ model:TalkfunSubjectExamineDetail)  {
        let count:Int = model.subjectAnswerList.count
        let x:CGFloat = (self.answerCardView.frame.size.width - CGFloat(count)*38-(CGFloat(count)-1)*11)/2.0
        for i in 0..<count {
            let btn = UIButton.init()
            let models = model.subjectAnswerList[i] as? TalkfunSubjectAnswer
            let string = models?.answer
            btn.setTitle(string, for: .normal)
            btn.addTarget(self, action: #selector(btnClick(btn:)), for: .touchUpInside)
            btn.frame = CGRect(x: x+(38+11)*CGFloat(i), y: (self.answerCardView.frame.size.height-38)/2.0, width: 38, height: 38)
            btn.tag = i
            btn.layer.borderWidth = 0.5;
            btn.backgroundColor = UIColor.white
            btn.layer.cornerRadius = 19

            btn.setTitleColor(UIColor(red: 78/255.0, green: 92/255.0, blue: 103/255.0, alpha: 1.0), for: .normal)
            btn.layer.borderColor = UIColor(red: 206/255.0, green: 217/255.0, blue: 227/255.0, alpha: 1.0).cgColor

            self.answerCardView.addSubview(btn)
            self.buttonArr.append(btn)
        }
    }
    
    @objc func btnClick(btn:UIButton) {
        
        if (self.optional == TalkfunTopicTypeIndividualEvent) {
            self.titleLab.text = "单选题";
            self.answerCardView.subviews.forEach { view in
                if view.isKind(of: UIButton.self) {
                    let btn1 = view as? UIButton
                    btn1?.setTitleColor(UIColor(red: 78/255.0, green: 92/255.0, blue: 103/255.0, alpha: 1.0), for: .normal)
                    btn1?.layer.borderColor = UIColor(red: 206/255.0, green: 217/255.0, blue: 227/255.0, alpha: 1.0).cgColor
                    btn1?.isSelected = false
                }
            }

            btn.setTitleColor(UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1.0), for: .normal)
            btn.layer.borderColor = UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1.0).cgColor
            btn.isSelected = true
        } else if (self.optional == TalkfunTopicTypeMultiple){
            self.titleLab.text = "多选题";
            btn.isSelected = !btn.isSelected
            if (btn.isSelected) {
                btn.setTitleColor(UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1.0), for: .normal)
                btn.layer.borderColor = UIColor(red: 23/255.0, green: 145/255.0, blue: 251/255.0, alpha: 1.0).cgColor
            } else {
                btn.setTitleColor(UIColor(red: 78/255.0, green: 92/255.0, blue: 103/255.0, alpha: 1.0), for: .normal)
                btn.layer.borderColor = UIColor(red: 206/255.0, green: 217/255.0, blue: 227/255.0, alpha: 1.0).cgColor
            }


        }
        

        
        
        
       
    }
    //开启答题卡倒计时
    @objc public func startAnswerCardSuccessTimers() {
        self.answerTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(clostBtnClick), userInfo: nil, repeats: false)
        RunLoop.main.add(self.answerTimer, forMode: RunLoop.Mode.common)
     
    }
    
    @objc public func addTimer(_ endTime:NSInteger)
    {
        self.endTime = endTime
        print("")
        self.initTimer()
    }
    
    func initTimer()
    {
        if((self.timer) == nil)
        {
            self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(startCountdown), userInfo: nil, repeats: true)
            RunLoop.main.add(self.timer! , forMode: RunLoop.Mode.default)
            self.timer.fire()
        }
    }
    
    @objc func startCountdown() {
//        print("endim==\(self.endTime)")
        if (TalkfunSharedTools.getCurrentDateString() <  self.endTime)
        
        {
            let countdownStr = TalkfunSharedTools.timeDifferenceAllSecond(endTime: self.endTime)
//            print("倒计时===\(countdownStr)")
            self.timeLab.text = "倒计时:" + "\(countdownStr as String)"
           
            
        }else
        {
            if self.timer != nil {
                self.timer.invalidate()
                self.timer = nil;
            }
           
          
            self.timeLab.text = "倒计时:"
            if self.endBlock != nil {
                self.endBlock!()
            }
          
            
            print("aaaaaaaa==\(TalkfunSharedTools.getCurrentDateString()),bb==\(self.endTime)")
        }
        
     
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

